package com.xwintop.xJavaFxTool.controller.games.brickblock;

import com.xwintop.xJavaFxTool.controller.games.core.WObject;
import com.xwintop.xJavaFxTool.controller.games.core.WScreen;
import com.xwintop.xJavaFxTool.controller.games.core.WSystem;
import javafx.animation.FadeTransition;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;

import java.util.concurrent.CopyOnWriteArrayList;

public class GameScreen extends WScreen {
	private BottomBrick bottomBrick = new BottomBrick();
	private Ball ball = new Ball(WSystem.WIDTH / 2, WSystem.HEIGHT - 40, 15);
	private CopyOnWriteArrayList<Brick> bricks = new CopyOnWriteArrayList<Brick>();

	public GameScreen(double width, double height) {
		super(width, height);

		initLevel();

		addObject(bottomBrick);
		addObject(ball);
	}

	@Override
	public void update() {
		super.update();
		if (ball.isCollisionWith(bottomBrick)) {
			ball.setSpeedY(-ball.getSpeedY());
		}

		for (Brick brick : bricks) {
			if (ball.isCollisionWith(brick)) {
				brick.setHp(brick.getHp() - 1);
				ball.setSpeedY(-ball.getSpeedY());
				if (brick.getHp() <= 0) {
					destroyObject(brick);
				}
				break;
			}
		}
	}

	private void destroyObject(final WObject brick) {
		FadeTransition fade = new FadeTransition(Duration.millis(200.0D), brick);
		fade.setFromValue(1.0D);
		fade.setToValue(0.0D);
		fade.setOnFinished(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent t) {
				getGraphicsContext2D().clearRect(brick.getX(), brick.getY(), brick.getWidth(), brick.getHeight());
			}
		});
		this.removeObject(brick);
		this.bricks.remove((Brick) brick);
		fade.play();
	}

	private void initLevel() {
		LevelLoader.load(this, 1);
	}

	public CopyOnWriteArrayList<Brick> getBricks() {
		return this.bricks;
	}

	@Override
	protected void onMouseMoved(MouseEvent event) {
		super.onMouseMoved(event);
		bottomBrick.onMouseMove(event);
	}

}
